package com.moshang.mall.cart.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moshang.mall.cart.vo.UserInfoDto;
import com.moshang.mall.constant.AuthConstant;
import com.moshang.mall.constant.CartConstant;
import com.moshang.mall.vo.MemberVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author moshang
 * @Package : com.moshang.mall.cart.interceptor
 * @date 2020-09-18
 * @Description : TODO
 **/
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoDto> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoDto userInfo=new UserInfoDto();
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        MemberVo memberVo = JSONObject.parseObject(JSON.toJSONString(attribute), MemberVo.class);
        if (memberVo!=null){
           //登录
             userInfo.setUserId(memberVo.getId());
       }
        Cookie[] cookies = request.getCookies();
       if (cookies!=null&&cookies.length>0){
           for (Cookie cookie:cookies){
               String name = cookie.getName();
               if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                   userInfo.setUserKey(cookie.getValue());
                   userInfo.setTempUser(true);
               }
           }
       }
       if (StringUtils.isEmpty(userInfo.getUserKey())){
           String uuid = UUID.randomUUID().toString();
           userInfo.setUserKey(uuid);
       }
        threadLocal.set(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
      UserInfoDto userInfo=threadLocal.get();
      if (!userInfo.isTempUser()) {
          Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfo.getUserKey());
          cookie.setDomain("mall.com");
          cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
          response.addCookie(cookie);
      }
    }
}
